// 加载环境变量
const config = require('dotenv').config({ path: `.env.${process.env.NODE_ENV}` });
const APP_CONFIG = config.parsed;
const mysql = require('mysql2/promise');

// 创建连接池
const pool = mysql.createPool({
  host: APP_CONFIG.MYSQL_HOST,
  user: APP_CONFIG.MYSQL_USER,
  password: APP_CONFIG.MYSQL_PASSWORD,
  port: APP_CONFIG.MYSQL_PORT,
  database: APP_CONFIG.MYSQL_DATANAME,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

// 测试数据库连接
(async () => {
  try {
    const connection = await pool.getConnection();
    const [rows, fields] = await connection.execute('SELECT VERSION() AS version');
    console.log('mysql init success! Database version:', rows[0].version);
    connection.release(); // 重要！释放连接
  } catch (error) {
    console.error('mysql init Failed to connect to the database:', error);
    // 如果连接失败，你可以选择在这里终止进程
    // process.exit(1);
  }
})();

module.exports = pool;